package net.bwie.realtime.vehicle2.job;

import com.alibaba.fastjson.JSON;
import net.bwie.realtime.jtp.common.utils.JdbcUtil;
import net.bwie.realtime.jtp.common.utils.KafkaUtil;
import net.bwie.realtime.vehicle2.bean.VehicleData;
import net.bwie.realtime.vehicle2.function.VehicleRealtimeStatusFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * 实时车辆状态监控
 * @Author: FuHe
 * @Date: 2025/6/7
 */
public class VehicleWindowRealtimeStatus2 {
    public static void main(String[] args) throws Exception {
        // 设置执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 读取数据源 kafka
        DataStream<String> kafkaStream = KafkaUtil.consumerKafka(env, "vehicle-data-log");
//        kafkaStream.print();
        // 处理数据
        DataStream<String> statusStream = handle(kafkaStream);
        statusStream.print();
        // 写入数据 clickhouse
        JdbcUtil.sinkToClickhouseUpsert(statusStream,
                "INSERT INTO vehicle_data.vehicle_status_report (" +
                        "   vin, speed, battery_level, battery_temp,\n" +
                        "   motor_temp, charging_status, energy_consumption)\n" +
                        "VALUES (?, ?, ?, ?, ?, ?, ?)");
        // 提交执行
        env.execute("VehicleWindowRealtimeStatus2");
    }

    private static DataStream<String> handle(DataStream<String> kafkaStream) {
        // 解析Kafka中的数据为VehicleData对象
        SingleOutputStreamOperator<VehicleData> map = kafkaStream.map(line -> JSON.parseObject(line, VehicleData.class));
        // 按vin分组
        KeyedStream<VehicleData, String> vehicleDataStringKeyedStream = map.keyBy(VehicleData::getVin);
        // 处理数据
        SingleOutputStreamOperator<String> process = vehicleDataStringKeyedStream.process(new VehicleRealtimeStatusFunction());
        return process;
    }
}
